<template>
	<div v-if="couponBase" v-loading="loading">
		<div class="coupon-info">
			<!-- 头部 -->
			<div class="app-main-top-box">
				<div class="title">券详情</div>
				<el-button size="medium" round @click="back">返回</el-button>
			</div>

			<!-- 券信息 -->
			<div class="flexRBC">
				<div>
					<div>
						<span class="coupon-name">{{ couponBase.couponName }}</span>
						&nbsp;&nbsp;
						<span class="coupon-type app-text-color-primary">{{ couponTypeOptions[couponBase.couponType] }}</span>
					</div>
					<div class="coupon-id">批次号：{{ couponBase.id }}</div>
				</div>
				<div v-if="!$store.getters.banBtnList.includes('BTN_MCH_COUPON_MANAGER_AND_PUT_ON')">
					<el-button
						v-if="couponBase.status == 1 && !couponBase.channelSync && ['cash_wx_busi', 'discount_wx_busi', 'cash_wx_pay'].includes(couponBase.couponType)"
						size="small"
						type="primary"
						round
						@click="syncCouponChannel(couponBase.id)"
					>
						同步券渠道
					</el-button>
					<el-button v-else-if="couponBase.status == 1" size="small" type="primary" round @click="changeStatus(1)">确认激活</el-button>
					<el-button
						v-if="
							couponBase.status == 1 &&
								((!couponBase.channelSync && ['cash_wx_busi', 'discount_wx_busi', 'cash_wx_pay'].includes(couponBase.couponType)) ||
									['cash', 'discount', 'exchange'].includes(couponBase.couponType))
						"
						type="info"
						size="small"
						round
						@click="editCoupon(couponBase.id)"
					>
						修改配置
					</el-button>
					<el-button v-if="couponBase.status == 2" size="small" type="warning" round @click="changeStatus(2)">暂停活动</el-button>
					<el-button v-if="couponBase.status == 3" size="small" round type="primary" @click="changeStatus(4)">重启活动</el-button>
					<el-button v-if="couponBase.status == 1 || couponBase.status == 2 || couponBase.status == 3" size="small" round type="danger" @click="changeStatus(3)">
						终止活动
					</el-button>
					<el-button v-if="couponBase.couponType === 'cash_wx_pay'" size="small" round type="danger" @click="downWxPayCouponVerifyRecord">导出微信核销记录</el-button>
				</div>
			</div>

			<!-- tab -->
			<div class="tab">
				<el-tabs v-model="tabName">
					<el-tab-pane label="详情" name="detail" />
					<el-tab-pane v-if="couponBase.status === 2 && !$store.getters.banBtnList.includes('BTN_MCH_COUPON_MANAGER_AND_PUT_ON')" label="领券二维码" name="code" />
					<el-tab-pane v-if="!$store.getters.banBtnList.includes('TAB_MCH_COUPON_PUT_ON_DATA')" label="发放数据" name="issue" />
					<el-tab-pane v-if="!$store.getters.banBtnList.includes('TAB_MCH_COUPON_CONSUME_DATA')" label="核销数据" name="verify" />
					<!-- <el-tab-pane v-if="couponDetail.couponTag == 1 && couponBase.status != 1" label="报名数据" name="sign" /> -->
					<!--BTN_MCH_COUPON_PUT_ON_DATA_EXPORT-->
					<!--BTN_MCH_COUPON_CONSUME_DATA_EXPORT-->
				</el-tabs>
			</div>
		</div>

		<div v-if="couponBase">
			<CouponDetail v-if="tabName === 'detail'" :coupon-base.sync="couponBase" @detail="getDetail" />
			<CouponCode v-if="tabName === 'code'" :coupon-base.sync="couponBase" />
			<IssueRecord v-if="tabName === 'issue'" :coupon-base.sync="couponBase" />
			<VerifyRecord v-if="tabName === 'verify'" :coupon-base.sync="couponBase" />
			<SignRecord v-if="tabName === 'sign'" :coupon-base.sync="couponBase" />
		</div>
	</div>
</template>

<script>
import CouponDetail from './CouponDetail';
import IssueRecord from './IssueRecord';
import VerifyRecord from './VerifyRecord';
import SignRecord from './SignRecord';
import CouponCode from './CouponCode';
import { mapGetters } from 'vuex';
import { couponStatus, syncWxCoupon, downWxPayCouponVerifyFile } from '../../../api/coupon';

export default {
	components: {
		CouponDetail,
		IssueRecord,
		VerifyRecord,
		CouponCode,
		SignRecord
	},
	data() {
		return {
			// 配置
			couponTypeOptions: {
				cash: '代金券',
				cash_wx_pay: '微信支付代金券',
				cash_wx_busi: '微信商家代金券',
				discount: '折扣券',
				discount_wx_busi: '微信商家折扣券',
				exchange: '兑换券'
			},
			resolve: null,
			reject: null,
			// 状态
			loading: false,
			// 数据
			tabName: 'detail',
			couponBase: null,
			detail: null,
			couponDetail: ''
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl'])
	},
	activated() {},
	mounted() {},
	methods: {
		/**
		 * 获取数据
		 */
		// 获取
		open(row) {
			this.couponBase = row;
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},
		getDetail(val) {
			this.couponDetail = val;
		},

		/**
		 * 按钮组
		 */
		// 返回
		back() {
			this.resolve && this.resolve();
		},

		// 改变状态
		changeStatus(status) {
			let { couponTag, signUpEndTime, endTime } = this.couponDetail; //couponTag：1商圈券 2普通券
			let signUpEndTimeStmp = new Date(signUpEndTime).getTime();
			let endTimeStmp = new Date(endTime).getTime();
			let curStamp = new Date().getTime();
			//商圈券 - 报名过期提示
			// if (couponTag == 1 && status == 1 && curStamp > signUpEndTimeStmp) {
			// 	this.$alert('报名时间已过期请重新设置报名时间', '提示', {
			// 		confirmButtonText: '确定',
			// 		callback: action => {}
			// 	});
			// 	return;
			// }
			const statusConfig = {
				1: {
					text: '激活卡券后，顾客将可以领取/购买，点击确定按钮立即激活！',
					successMsg: '激活成功',
					status: 2,
					confirmButtonText: '确认激活'
				},
				2: {
					text: '暂停活动后，优惠券将不会继续发放，直到下一次人工重启活动！',
					successMsg: '暂停成功',
					status: 3,
					confirmButtonText: '确认暂停'
				},
				3: {
					text: '终止活动后，优惠券将不会继续发放且不可再重启，但是不会影响已经投放的优惠券！',
					successMsg: '终止成功',
					status: 4,
					confirmButtonText: '确认终止'
				},
				4: {
					text: '重启卡券活动后，顾客将可以领取/购买，点击确定按钮立即重启！',
					successMsg: '重启成功',
					status: 2,
					confirmButtonText: '确认重启'
				}
			};

			//商圈券 - 提前终止活动
			if (couponTag == 1 && status == 3 && curStamp < endTimeStmp) {
				statusConfig[status].text = '当前优惠券活动时间还未结束，终止后将不影响已领取的用户使用';
			}
			this.$confirm(statusConfig[status].text, '提示', {
				confirmButtonText: statusConfig[status].confirmButtonText,
				cancelButtonText: '取消',
				type: 'warning',
				center: true,
				roundButton: true
			}).then(() => {
				let params = '';
				params = {
					stockId: this.couponBase.id,
					status: status
				};
				this.loading = true;
				couponStatus(params)
					.then(res => {
						this.$notify({
							title: '成功',
							message: statusConfig[status].successMsg,
							type: 'success',
							duration: 2000,
							offset: 40
						});
						this.couponBase.status = statusConfig[status].status;
						console.log(this.couponBase);
					})
					.catch(err => {})
					.finally(() => {
						this.loading = false;
					});
			});
		},

		// 同步渠道
		syncCouponChannel(couponId) {
			this.loading = true;
			syncWxCoupon({ couponId })
				.then(res => {
					this.$notify({
						title: '成功',
						message: '同步成功',
						type: 'success',
						duration: 2000,
						offset: 40
					});
					this.couponBase.channelSync = true;
				})
				.finally(() => {
					this.loading = false;
				});
		},

		// 跳转编辑
		editCoupon(id) {
			this.$router.push({
				name: 'PublicCardsAndOfferEditCoupon',
				query: { mode: 'edit', id }
			});
		},

		// 导出微信核销记录
		downWxPayCouponVerifyRecord() {
			if (this.couponBase.status !== 4 && this.couponBase.status !== 5) {
				this.$message.error('待券到期后方可导出核销记录');
				return;
			}
			var alink = document.createElement('a');
			alink.href =
				process.env.VUE_APP_BASE_API + '/couponAdmin/coupon/wxPayCouponVerifyFile?couponId=' + this.couponBase.id + '&X-BUSINESS-TOKEN=' + this.$store.state.user.token;
			alink.download = '';
			alink.click();
			// downWxPayCouponVerifyFile({ couponId: this.couponBase.id }).then(res => {
			//   this.downloadFile(res.data)
			// }).catch((err) => {
			//   this.downloadFile(err)
			// })
		},

		// 下载文件
		downloadFile(data, fileName = '导出表格.csv') {
			if (!data) {
				return;
			}
			const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }));
			const link = document.createElement('a');
			link.style.display = 'none';
			link.href = url;
			link.setAttribute('download', fileName);
			document.body.appendChild(link);
			link.click();
		}
		/**
		 * 状态组
		 */
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.coupon-info {
	::v-deep {
		.el-tabs__header {
			margin-bottom: 0;
			background-color: #fff;
			border-radius: 0 0 5px 5px;
		}

		.el-tabs__nav-wrap::after {
			background-color: #fff;
		}

		.el-tabs__active-bar {
			height: 4px;
		}

		.el-row {
			flex-wrap: wrap;
		}

		.el-card,
		.el-card__body {
			height: 100%;
		}
	}

	padding: 24px 30px 0;
	border-radius: 5px 5px;
	background-color: #fff;
	margin-bottom: 10px;

	.coupon {
		&-name {
			font-size: 20px;
			font-weight: bold;
		}

		&-type {
			font-size: 14px;
		}

		&-id {
			margin-top: 10px;
			font-size: 14px;
			color: #909399;
		}
	}
}
</style>
